import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { RootState } from './store'
import { delTodo, addTodo, updateTodo, getTodos} from './store/actions/index'
export default function App() {
    const todos = useSelector((state:RootState) => state.todos)
    const dispatch = useDispatch()
    const doDel = (id: number) => {
        dispatch(delTodo(id))
    }

    const [name, setName] = useState('')
    const onChange = (e:React.ChangeEvent<HTMLInputElement>) => {
        
        setName(e.target.value)
    }
    const onKeyup = (e: React.KeyboardEvent<HTMLInputElement>) => {
        console.log(e.key === 'Enter')
        // if( e.keyCode === 13 ) {
        if(e.key === 'Enter') {
           dispatch(addTodo(name))

           setName('')
        }
    }
    const updateState = (id:number) => {
        // alert(id)
        dispatch(updateTodo(id))
    }

    useEffect(() => {
        dispatch(getTodos())
    }, [dispatch])
    return (
        <div>
            <h2>todos</h2>
            <p>
                <input value={name} onKeyUp={onKeyup} onChange={onChange}/>
            </p>
            <hr/>
            {
                todos.map((it) => (<p key={it.id}>
                    <label onClick={()=>updateState(it.id)} className={it.isDone ? 'complete' : ''}>{it.name}</label> -- <button onClick={()=>{
                    doDel(it.id)
                }}>del</button></p>))
            }
            <button onClick={()=>{
                // dispatch<{type:string,a:number}>({type: 'abc', a:100})
                dispatch({type: 'abc', a:100})
            }}>do</button>
        </div>
    )
}
